#version 330 core
out vec4 FragColor;  // 输出片段颜色

in vec2 TexCoord;
in vec3 Normal;
in float AoIntensity;
in float Smoothness; // 光滑度
in vec3 FragPos;

uniform sampler2D diffuseTexture;
uniform sampler2D normalMap;
uniform float alphaThreshold = 0.3;
uniform vec3 cameraPos;

vec3 calcDiffuse(vec3 normal, vec3 lightDir, vec3 lightColor){
    float diff = max(dot(normal, lightDir), 0.0);
    return lightColor * diff;
}

vec3 calcFogColor(vec3 fragPos){
    fragPos = normalize(fragPos);
    vec3 skyColor = vec3(0.39608, 0.60392, 0.69020);
    float miePhase = 1.0 / (4.0 * 3.14159);  // 简化Mie散射相位函数
    float rayleighPhase = 3.0 / (16.0 * 3.14159) * (1.0 + fragPos.y * fragPos.y);  // Rayleigh散射
    float scattering = rayleighPhase * 0.8 + miePhase * 0.2;  // 混合散射

    // 根据高度角调整散射强度
    float heightFactor = pow(1.0 - abs(fragPos.y), 4.0);  // 靠近地平线时散射更强
    vec3 scatteredColor = skyColor * scattering * heightFactor * 7.5;

    vec3 envColor = vec3(0.52941, 0.80784, 0.92157);
    vec3 finalColor = envColor + scatteredColor;
    return finalColor;
}

vec3 useNormalMap(){
    // 直接从法线贴图获取切线空间法线 [0,1] -> [-1,1]
    vec3 tangentNormal = texture(normalMap, TexCoord).rgb * 2.0 - 1.0;

    // 直接在片段着色器中计算切线和副切线
    vec3 N = normalize(Normal);

    // 计算切线向量 - 使用纹理坐标的梯度作为参考
    vec3 dp1 = dFdx(FragPos);
    vec3 dp2 = dFdy(FragPos);
    vec2 duv1 = dFdx(TexCoord);
    vec2 duv2 = dFdy(TexCoord);

    // 计算切线和副切线
    vec3 dp2perp = cross(dp2, N);
    vec3 dp1perp = cross(N, dp1);
    vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;
    vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;

    // 计算反转纹理坐标的比例因子
    float invmax = inversesqrt(max(dot(T, T), dot(B, B)));
    T = T * invmax;
    B = B * invmax;

    // 构建TBN矩阵
    mat3 TBN = mat3(T, B, N);

    // 将法线从切线空间转换到世界空间
    return normalize(TBN * tangentNormal);
}

void main()
{
    vec4 texColor = texture(diffuseTexture, TexCoord);
    if(texColor.a < alphaThreshold) discard;

    vec3 norm = normalize(Normal);
    vec3 lightDir = normalize(vec3(0.0, 0.5, 1.0));




    float intensity = 0.4;// 光强
    vec3 lightColor = vec3(1.0 * intensity * Smoothness, 0.843137 * intensity * Smoothness, 0.0);// 金黄色
    vec3 diffuse = calcDiffuse(norm, lightDir, lightColor);


    float saturation = 0.75;// 饱和度
    float luminance = dot(texColor.rgb, vec3(0.299, 0.587, 0.114));
    vec3 desaturated = mix(vec3(luminance), texColor.rgb, saturation);


    vec4 color1 = vec4(desaturated + diffuse, texColor.a);

    float fogStart = 37.5;
    float fogEnd = 187.5;
    vec4 fogColor = vec4(calcFogColor(FragPos + cameraPos), 1.0);
    // 计算雾效因子
    float fogFactor = (fogEnd - length(FragPos + cameraPos)) / (fogEnd - fogStart);
    fogFactor = clamp(fogFactor, 0.0, 1.0);

    vec4 finalColor = vec4(color1.rgb * (1 - AoIntensity), texColor.a);

    finalColor = mix(finalColor, fogColor, 1 - fogFactor);

    FragColor = finalColor; // 设置片段颜色
}